<template>
  <!-- 追溯码 -->
  <el-dialog v-model="open" :close-on-click-modal="false" :title="'填写追溯码'" append-to-body width="60%"
             @close="dialogClose">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-table :border="true" :data="form.traceabilityCodeList" :header-cell-style="$headerCellStyle"
                ref="tableRef" :span-method="objectSpanMethod"
                :stripe="true"
                height="600" highlight-current-row>
        <el-table-column :align="'center'" label="追溯码" min-width="150" prop="trackCode">
          <template #default="scope">
            <el-form-item
              :rules="rules.trackCode" class="table-form-margin">
              <el-input :key="scope.$index " :ref="(el) => inputRefs[scope.$index] = el" v-model="scope.row.trackCode"
                        clearable @keydown.enter.prevent="handleEnter(scope.$index)"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" header-align="center" label="领药人信息" prop="name" width="160">
          <template #default="scope">
            <span class="ml5 ys-css">
              {{ scope.row.name }}
                <span style="margin-left: -10px">
                            <svg-icon :icon-class="dictStore.getMateDictInfo(
                                dictDataMap['sys_user_sex'],
                                scope.row.sex
                            ).dictValue === '1'
                                ? 'man'
                                : 'woman'
                                " style="margin-left: 10px"/>
                        </span>
                {{ scope.row.ageAll }}
            </span>
          </template>
        </el-table-column>
        <el-table-column :align="'left'" header-align="center" label="药品" prop="drugName" width="220">
          <template #default="scope">
            <span class="ml5">{{ scope.row.drugName }}</span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="packageSpec"
                         width="130"/>
        <el-table-column :align="'center'" header-align="center" label="数量" prop="num" width="100">
          <template #default="scope">
          <span>{{ scope.row.num }} <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.packSize === '1' ?
                        scope.row.minUnits : scope.row.packageUnits" style="margin: -23px -20px 0px 27px"/>
          </span>
          </template>
        </el-table-column>
        <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                         width="110"/>
        <el-table-column :align="'left'" header-align="center" label="序号" prop="num" width="100">
          <template #default="scope">
            <span><span class="mr5">第</span>{{ scope.row.numSort }} <dict-data-tag :options="dictDataMap['spec_unit']"
                                                                                    :value="scope.row.packSize === '1' ?
                        scope.row.minUnits : scope.row.packageUnits" style="margin: -23px -20px 0px 27px"/>
          </span>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <template #footer>
                <span class="dialog-footer">
                    <el-button type="success" @click="refresh">刷新</el-button>
                    <el-button type="danger" @click="clear">清空</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                    <el-button @click="dialogClose">取 消</el-button>
                </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {useDictStoreHook} from "@/store/modules/dict.ts";
import {getPrescTraceabilityCodeList} from "@/api/patient/prescriptionApply.ts"
import {getOrdersTraceabilityCodeList} from "@/api/orders/orders.ts"
import {ElInput} from "element-plus";

const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'sys_user_sex'))

const emits = defineEmits(["submitFormOk"])
const props = defineProps({
  // 机构id
  orgId: {
    type: String,
    default: ''
  }
})

// 创建一个 ref 数组来存储 input 框的引用
const inputRefs = ref<Array<InstanceType<typeof ElInput>>>([]);
const tableRef = ref()
const open = ref(false)
const formRef = ref()
const form = ref<any>({traceabilityCodeList: [{trackCode: "111"}]})

// 父组件传的值
const obj = ref<any>({})
// 表单校验
const rules = ref({
  trackCode: [
    {required: true, message: "追溯码不能为空", trigger: "blur"}
  ]
})

// 处理回车键事件
const handleEnter = (index: number) => {
  debugger
  // 计算下一个 input 框的索引
  const nextIndex = index + 1;
  // 如果下一个索引在数组范围内，则将焦点转移到下一个 input 框
  if (nextIndex < form.value.traceabilityCodeList.length) {
    inputRefs.value[nextIndex]?.focus();
    tableRef.value.setCurrentRow(form.value.traceabilityCodeList[nextIndex])
  } else if (nextIndex >= form.value.traceabilityCodeList.length) {
    inputRefs.value[0].focus();
    tableRef.value.setCurrentRow(form.value.traceabilityCodeList[0])
  }
};

/**
 * 刷新列表
 */
function refresh() {
  getList()
}

/**
 * 清空填写的追溯码
 */
function clear() {

}

/**
 * 父级页面 打开组件
 */
function initOpenTraceabilityCode(objThis: any) {
  open.value = true
  obj.value = {
    applyIds: objThis.ids,
    type: objThis.type,
    orgId: props.orgId
  }
  getList()
}

function getList() {
  if (obj.value.type === '1') {
    getPrescTraceabilityCodeList(obj.value).then(res => {
      //处方发药
      form.value.traceabilityCodeList = res.data
    })
  } else if (obj.value.type === '2') {
    // 医嘱摆药
    getOrdersTraceabilityCodeList(obj.value).then(res => {
      form.value.traceabilityCodeList = res.data
    })
  }
}

/**
 * 关闭弹出框
 */
function dialogClose() {
  form.value.traceabilityCodeList = []
  open.value = false
}

/**
 * 提交保存追溯码
 */
function submitForm() {
  (formRef.value as any).validate(valid => {
    if (valid) {
      emits("submitFormOk", form.value)
    }
  })
}


/** 表格合并列和行 */
function objectSpanMethod({row, column, rowIndex, columnIndex}) {
  if (columnIndex === 1 || columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
    const _row = flitterData(form.value.traceabilityCodeList, columnIndex).one[rowIndex];
    const _col = _row > 0 ? 1 : 0;
    return {
      rowspan: _row,
      colspan: _col,
    };
  }
}

/**合并表格的第一列，处理表格数据 */
function flitterData(arr, columnIndex) {
  let spanOneArr: any = [];
  let concatOne = 0;
  arr.forEach((item, index) => {
    if (index === 0) {
      spanOneArr.push(1);
    } else {
      //注意这里的quarterly是表格绑定的字段，根据自己的需求来改
      if (columnIndex === 2 || columnIndex === 3 || columnIndex === 4) {
        if (item.num === arr[index - 1].num && item.itemId === arr[index - 1].itemId) {
          //第3 4 5列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      } else if (columnIndex === 1) {
        if (item.name === arr[index - 1].name && item.ageAll === arr[index - 1].ageAll) {
          //第一列需合并相同内容的判断条件
          spanOneArr[concatOne] += 1;
          spanOneArr.push(0);
        } else {
          spanOneArr.push(1);
          concatOne = index;
        }
      }
    }
  });
  return {
    one: spanOneArr,
  };
}

defineExpose({
  initOpenTraceabilityCode,
  dialogClose
})
</script>

<style scoped>

</style>
